package com.jic.product.impl;

import java.io.InputStream;
import java.lang.Long;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.jic.common.base.vo.RestResult;
import com.jic.product.constant.consist.ResponseCode;
import com.jic.product.entity.ProductPrice;
import com.jic.product.entity.ProductPriceAudit;
import com.jic.product.entity.StoreInventory;
import com.jic.product.exception.AppRuntimeException;
import com.jic.product.manage.request.ProductBatchUpdateRequest;
import com.jic.product.manage.request.ProductPriceRequest;
import com.jic.product.manage.response.ProductPriceResponse;
import com.jic.product.mapper.ProductPriceAuditMapper;
import com.jic.product.mapper.ProductPriceMapper;
import com.jic.product.mapper.StoreInventoryMapper;
import com.jic.product.service.ProductPriceService;
import com.jic.common.base.vo.Page;
import com.jic.common.base.vo.PageResult;

import com.jic.product.util.ExcelImportUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

/**
 * 价格表
 *
 * @author :
 * @version : v1.0.0
 * @email :
 * @since : 2020-01-10 07:03:01
 */
@Service
@Slf4j
public class ProductPriceServiceImpl implements ProductPriceService {

    @Resource
    private ProductPriceMapper productPriceMapper;

    @Resource
    private ProductPriceAuditMapper productPriceAuditMapper;
    @Autowired
    private StoreInventoryMapper storeInventoryMapper;

    @Override
    public long insert(ProductPrice productPrice) {
        long flag = productPriceMapper.insert(productPrice);
        //修改库存
        StoreInventory storeInventory1 = storeInventoryMapper.queryByProductId(productPrice.getProductId());
        StoreInventory storeInventory=new StoreInventory();
        storeInventory.setProductId(productPrice.getProductId());
        storeInventory.setAvailableStock(productPrice.getAvailableStock());
        storeInventory.setTotalStock(productPrice.getTotalStock());
        if(null!=storeInventory1){
            storeInventoryMapper.updateByProductId(storeInventory);
        }else{
            storeInventoryMapper.insert(storeInventory);
        }
        return flag;
    }

    @Override
    public long delete(Long id) {
        return productPriceMapper.delete(id);
    }

    @Override
    public long update(ProductPrice productPrice) {
        return productPriceMapper.update(productPrice);
    }

    @Override
    public ProductPrice queryByPrimaryKey(Long id) {
        return productPriceMapper.queryByPrimaryKey(id);
    }

    @Override
    public List<ProductPrice> query(ProductPrice productPrice) {
        return productPriceMapper.query(productPrice);
    }

    @Override
    public PageResult<ProductPrice> queryPage(ProductPrice productPrice, Page pageQuery) {
        //计算下标
        int startIndex = (pageQuery.getStart() - 1) * pageQuery.getLimit();
        List<ProductPrice> list = productPriceMapper.queryPage(startIndex, pageQuery.getLimit(), productPrice);
        long count = productPriceMapper.queryPageCount(productPrice);
        PageResult pageResult = new PageResult();
        pageResult.setRows(list);
        pageResult.setTotal(count);
        return pageResult;
    }

    @Override
    public ProductPrice getProductPrice(ProductPrice productPrice) {

        return productPriceMapper.getProductPrice(productPrice);
    }

    @Override
    public long updateProductPrice(ProductPriceRequest productPriceRequest) {
        //更新子品价格
        ProductPrice productPrice = new ProductPrice();
        productPrice.setProductId(productPriceRequest.getProductId());
        productPrice.setMarketPrice(productPriceRequest.getMarketPrice());
        productPrice.setSaleTaxRate(productPriceRequest.getSaleTaxRate());
        productPrice.setPurchaseTaxRate(productPriceRequest.getPurchaseTaxRate());
        productPrice.setPlatformServiceFee(productPriceRequest.getPlatformServiceFee());
        productPrice.setAvailableStock(productPriceRequest.getAvailableStock());
        productPrice.setTotalStock(productPriceRequest.getTotalStock());
        //商家商品才审核操作
        if (null!=productPriceRequest.getDataType() && productPriceRequest.getDataType() == 2) {
            //是否有审核记录 0否 其它有
            if (productPriceRequest.getIsAudit() == 0) {
                //查询改动前的值
                ProductPrice productPrice1 = productPriceMapper.getProductPrice(productPrice);
                //金额相同不做审核处理
                if (productPrice1.getSalePriceWithTax().compareTo(productPriceRequest.getSalePriceWithTax()) != 0) {
                    ProductPriceAudit productPriceAudit = new ProductPriceAudit();
                    BeanUtils.copyProperties(productPriceRequest, productPriceAudit);
                    productPriceAudit.setBeforeValue(productPrice1.getSalePriceWithTax());
                    productPriceAudit.setAfterValue(productPriceRequest.getSalePriceWithTax());
                    productPriceAudit.setProductId(productPriceRequest.getProductId());
                    productPriceAudit.setStatus(0L);
//                    productPriceAudit.setDataType(2);
                    productPriceAuditMapper.insertProductPriceAudit(productPriceAudit);
                }
            }
        } else {
            productPrice.setSalePriceWithTax(productPriceRequest.getSalePriceWithTax());
        }
        productPrice.setGroupBuyingPrice(productPriceRequest.getGroupBuyingPrice());
        productPrice.setPurchasePriceWithTax(productPriceRequest.getPurchasePriceWithTax());
        productPrice.setUpdateTime(new Date());
        productPrice.setUpdater(productPriceRequest.getUpdater());
        productPrice.setUpdaterName(productPriceRequest.getUpdaterName());
        productPriceMapper.updateProductDistributeStore(productPrice);
        //修改库存
        StoreInventory storeInventory1 = storeInventoryMapper.queryByProductId(productPrice.getProductId());
        StoreInventory storeInventory=new StoreInventory();
        storeInventory.setProductId(productPriceRequest.getProductId());
        storeInventory.setAvailableStock(productPriceRequest.getAvailableStock());
        storeInventory.setTotalStock(productPriceRequest.getTotalStock());
        if(null!=storeInventory1){
            storeInventoryMapper.updateByProductId(storeInventory);
        }else{
            storeInventoryMapper.insert(storeInventory);
        }
        return 0;
    }

    @Override
    public ProductPriceResponse queryProductPrice(ProductPriceRequest price) {
        return productPriceMapper.queryProductPrice(price);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestResult batchUpdateProductPrice(ProductBatchUpdateRequest productBatchUpdateRequest) {
        log.info("开始进入批量修改商品价格------------》" + productBatchUpdateRequest.toString());
        try {
            if (productBatchUpdateRequest != null && CollectionUtils.isNotEmpty(productBatchUpdateRequest.getProductBatchUpdateRequestList())) {
                productBatchUpdateRequest.getProductBatchUpdateRequestList().forEach(item -> {
                    ProductBatchUpdateRequest pro = new ProductBatchUpdateRequest();
                    pro.setNum(item.getNum());
                    pro.setId(item.getId());
                    productPriceMapper.batchUpdateProductPrice(pro);
                });
            } else {
                return RestResult.error("9999", "参数异常");
            }
        } catch (Exception e) {
            log.error("修改商品价格异常", e);
            throw new AppRuntimeException(ResponseCode.EXCEPTION);
        }
        return RestResult.success(true);
    }


    /**
     * 通过导入店铺商品修改商品价格
     *
     * @param fileName
     * @param file
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestResult byExcelUpdateProductPrice(String fileName, MultipartFile file) throws Exception {
        //验证EXCEL文件
        if (!ExcelImportUtils.validateExcel(fileName)) {
            return RestResult.error("9999", "上传文件格式不正确");
        }
        InputStream is = file.getInputStream();
        Workbook wb = null;
        Map<String, PictureData> mapList = null;
        //店铺商品
        Sheet sheet = null;
        //2003的excel
        if (ExcelImportUtils.isExcel2003(fileName)) {
            wb = new HSSFWorkbook(is);
        } else {
            wb = new XSSFWorkbook(is);
        }
        sheet = wb.getSheetAt(0);
        if (sheet == null) {
            return RestResult.error("9999", "数据不存在");
        }
        //r = 2 表示从第三行开始循环 如果你的第三行开始是数据
        List<ProductBatchUpdateRequest> productBatchUpdateRequestList = new ArrayList<>();
        for (int r = 1; r <= sheet.getLastRowNum(); r++) {
            //通过sheet表单对象得到 行对象
            Row row = sheet.getRow(r);
            if (row == null) {
                continue;
            }
            //导入数据请求
            ProductBatchUpdateRequest productBatchUpdateRequest = new ProductBatchUpdateRequest();
            //共4列表数据
            for (int j = 0; j < 4; j++) {
                Cell cell = row.getCell(j);
                if (cell != null) {
                    cell.setCellType(CellType.STRING);
                    if (j == 0) {
                        productBatchUpdateRequest.setId(Long.valueOf(cell.getStringCellValue()));
                    } else if (j == 3) {
                        productBatchUpdateRequest.setNum(Long.valueOf(cell.getStringCellValue()));
                    }
                }
            }
            productBatchUpdateRequestList.add(productBatchUpdateRequest);

        }
        ProductBatchUpdateRequest productBatchUpdateRequest1 = new ProductBatchUpdateRequest();
        productBatchUpdateRequest1.setProductBatchUpdateRequestList(productBatchUpdateRequestList);
        if (CollectionUtils.isNotEmpty(productBatchUpdateRequest1.getProductBatchUpdateRequestList())) {
            this.batchUpdateProductPrice(productBatchUpdateRequest1);
        }
        return RestResult.success(true);
    }
}
